<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'CreateNotifyBotModal'
});

interface Props {
  visible: boolean;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submit', params: Api.Outbound.CreateNotifyBotParams): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();

const model: Api.Outbound.CreateNotifyBotParams = reactive(createDefaultModel());

function createDefaultModel(): Api.Outbound.CreateNotifyBotParams {
  return {
    name: '',
    groupName: '',
    text: '',
    timbresValue: 'BV007_GPU',
    variableDefines: []
  };
}

const rules = computed<Record<keyof Api.Outbound.CreateNotifyBotParams, App.Global.FormRule>>(() => {
  const { defaultRequiredRule } = useFormRules();

  return {
    name: defaultRequiredRule,
    groupName: defaultRequiredRule,
    text: defaultRequiredRule,
    timbresValue: [],
    variableDefines: []
  };
});

const timbresOptions = [
  { label: 'BV007_GPU (推荐)', value: 'BV007_GPU' },
  { label: 'BV001_GPU', value: 'BV001_GPU' },
  { label: 'BV002_GPU', value: 'BV002_GPU' },
  { label: 'BV003_GPU', value: 'BV003_GPU' },
  { label: 'BV004_GPU', value: 'BV004_GPU' },
  { label: 'BV005_GPU', value: 'BV005_GPU' },
  { label: 'BV006_GPU', value: 'BV006_GPU' }
];

function handleInitModel() {
  Object.assign(model, createDefaultModel());
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  emit('submit', { ...model });
}

function addVariable() {
  if (!model.variableDefines) {
    model.variableDefines = [];
  }
  model.variableDefines.push({
    name: '',
    key: ''
  });
}

function removeVariable(index: number) {
  if (model.variableDefines) {
    model.variableDefines.splice(index, 1);
  }
}

watch(visible, newValue => {
  if (newValue) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :mask-closable="false" preset="card" title="创建通知剧本" class="w-700px">
    <NForm ref="formRef" :model="model" :rules="rules" size="small" :label-width="100">
      <NGrid :cols="24" :x-gap="18">
        <NFormItemGridItem :span="24" label="剧本名称" path="name">
          <NInput v-model:value="model.name" placeholder="请输入剧本名称" />
        </NFormItemGridItem>
        <NFormItemGridItem :span="24" label="项目组名称" path="groupName">
          <NInput v-model:value="model.groupName" placeholder="请输入项目组名称" />
        </NFormItemGridItem>
        <NFormItemGridItem :span="24" label="音色配置" path="timbresValue">
          <NSelect
            v-model:value="model.timbresValue"
            placeholder="请选择音色配置"
            :options="timbresOptions"
          />
        </NFormItemGridItem>
        <NFormItemGridItem :span="24" label="播报文本" path="text">
          <NInput
            v-model:value="model.text"
            type="textarea"
            placeholder="请输入播报文本，使用 {%变量名%} 引用变量，例如：您好 {%name%}，这是一条通知消息"
            :rows="4"
          />
          <div class="text-12px text-gray-500 mt-4px">
            提示：在文本中使用 {%变量名%} 格式来引用变量，变量名需要与下方定义的调用名一致
          </div>
        </NFormItemGridItem>
        <NFormItemGridItem :span="24" label="变量定义">
          <div class="w-full space-y-8px">
            <div v-if="!model.variableDefines || model.variableDefines.length === 0" class="text-gray-500">
              暂无变量，点击下方按钮添加变量
            </div>
            <div
              v-for="(variable, index) in model.variableDefines"
              :key="index"
              class="flex items-center gap-8px"
            >
              <NInput
                v-model:value="variable.name"
                placeholder="变量名字（中文）"
                style="flex: 1"
              />
              <NInput
                v-model:value="variable.key"
                placeholder="调用名（英文）"
                style="flex: 1"
              />
              <NButton type="error" size="small" ghost @click="removeVariable(index)">
                删除
              </NButton>
            </div>
            <NButton type="primary" dashed size="small" @click="addVariable">
              <template #icon>
                <icon-ic-round-plus class="text-icon" />
              </template>
              添加变量
            </NButton>
            <div class="text-12px text-gray-500">
              变量名字：显示名称，用于界面展示；调用名：在播报文本中使用的变量名
            </div>
          </div>
        </NFormItemGridItem>
      </NGrid>
    </NForm>
    <template #footer>
      <NSpace :size="16">
        <NButton @click="closeModal">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
